import React, { useEffect, useLayoutEffect, useState } from 'react'

function Contact() {
    const [userData, setUserData] = useState(null)
    const [userId, setUserId] = useState('1')
    const [loading, setLoading] = useState(true)

    const scrollHandler = (e) => {
        const scrollTop = e.currentTarget.scrollTop
        window.history.replaceState({}, '', `?top=${scrollTop}`)
    }

    useEffect(() => {
        setLoading(true)
        fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
            .then(response => response.json())
            .then(data => {
                setUserData(data)
                setLoading(false)
            })
    }, [userId])

    useLayoutEffect(() => {
        const container = document.querySelector('#container')
        const scrollTop = window.location.search.split('=')[1]
        container.scrollTop = Number(scrollTop) | 0
    }, [])

    return (
        <div>
            <h1 className="title">Contact</h1>
            <div>Welcome to Contact!</div>

            <div onScroll={scrollHandler} id='container' style={{ height: '500px', overflow: 'auto', marginBottom: '20px'}}>
                {
                    Array.from({ length: 500 }).map((item, index) => {
                        return <div key={index}>{index + 1}</div>
                    })
                }
            </div>

            <div>
                <input value={userId} onChange={(e) => setUserId(e.target.value)} type="text" placeholder="Name" />
                <div>
                    {loading ?
                        (<div>Loading...</div>)
                        : (<div>
                            <div>Name: {userData?.name}</div>
                            <div>Email: {userData?.email}</div>
                            <div>Username: {userData?.username}</div>
                            <div>Phone: {userData?.phone}</div>
                            <div>Website: {userData?.website}</div>
                        </div>)}
                </div>
            </div>

        </div>
    )
}

export default Contact